package com.hy;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenzeke
 * @date 2019/9/5 13:10
 */
@Slf4j
public class HttpUtil {
    public static String defaultContentType = "text/html; charset=UTF-8";
    public static String imageContentType = "image/jpg";
    private static CookieStore cookieStore = new BasicCookieStore();

    public static DefaultHttpClient getBuilder() {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.setCookieStore(cookieStore);
        return httpclient;
    }

    public static String doGet(String url) throws Exception {
        return doGet(url, defaultContentType);
    }

    public static String doPost(String url, String content) throws Exception {
        HttpPost request = new HttpPost(url);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("html", content));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
        request.setEntity(entity);
        HttpResponse response = getBuilder().execute(request);

        String content1 = EntityUtils.toString(entity);
        log.info("请求响应数据===========================》" + content1);

        // 判断是否正常返回
        if (response.getStatusLine().getStatusCode() == 200) {
            // 解析数据
            HttpEntity resEntity = response.getEntity();
            String data = EntityUtils.toString(resEntity);
            return data;
        }
        return null;
    }


    public static void test(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        url = "https://ups.bdp.cn/api/saml/sso?domain=xdgjsc";
        HttpClientContext httpClientContext = HttpClientContext.create();
        CookieStore cookieStore = new BasicCookieStore();
        httpClientContext.setCookieStore(cookieStore);
        RequestConfig config = RequestConfig.custom().setRedirectsEnabled(true).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
        HttpGet httpGet = HttpClientUtils.doGetHandle(url, headers, params);
        HttpClientResult httpClientResult = HttpClientUtils.getHttpClientResult(httpClient, httpGet, httpClientContext);
        log.info("" + httpClientResult.getContent().length());
        log.info(JSON.toJSONString(httpGet.getAllHeaders()));
        log.info(JSON.toJSONString(cookieStore.getCookies()));


        Thread.sleep(3000);

        //https://www.22408.cn/idp/profile/SAML2/Redirect/SSO?execution=e1s2
        url = "https://www.22408.cn/idp/profile/SAML2/Redirect/SSO?execution=e1s2";
        url = "https://www.22408.cn/idp/profile/SAML2/Redirect/SSO";
        url = "https://www.22408.cn/idp/profile/SAML2/Redirect/SLO";
        params = new HashMap<>();
        params.put("j_username", "a");
        params.put("j_password", "a");
        headers = new HashMap<>();

        HttpPost httpPost = HttpClientUtils.doPosthandle(url, headers, params);
        HttpClientResult httpClientResult1 = HttpClientUtils.getHttpClientResult(httpClient, httpPost, httpClientContext);
        log.info(httpClientResult1.getContent());

        return;
    }

    public static void main(String[] args) throws Exception {
        test(null, null, null);
    }

    public static String doGet(String url, String contentType) throws Exception {
        HttpGet request = new HttpGet(url);
        //设置cookie
        CloseableHttpResponse response = getBuilder().execute(request);
        response.setHeader("content-type", contentType);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        //更新cookie
        String content = EntityUtils.toString(entity);
        log.info("请求响应数据===========================》" + content);
        int code = response.getStatusLine().getStatusCode();
        if (503 == code) {
            String body = IOUtils.toString(inputStream, "utf-8");
            log.info("请求返回503状态码，error body==>" + body);
            return null;
        }
        if (imageContentType.equals(contentType)) {
            String result = ImageUtil.getImageCode(inputStream);
            log.info("图片识别===>" + result);
            return result;
        } else {
            String body = IOUtils.toString(inputStream, "utf-8");
            return body;
        }
    }

    /**
     * 获取图片验证码
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGetImage(String url) throws Exception {
        HttpGet request = new HttpGet(url);
        CloseableHttpResponse response = getBuilder().execute(request);
        response.setHeader("content-type", imageContentType);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        String result = ImageUtil.getImageCode(inputStream);
        log.info("图片识别===>" + result);
        return result;
    }

}
